<?php

namespace app\admin\controller;

use app\admin\model\Fields as ModelFields;
use app\admin\model\Store;
use app\common\controller\Backend;
use think\facade\Db;
use think\facade\Queue;

/**
 * 数据字段配置
 */
class Fields extends Backend
{
    /**
     * Fields模型对象
     * @var object
     * @phpstan-var \app\admin\model\Fields
     */
    protected object $model;

    protected array|string $preExcludeFields = ['id', 'create_time', 'update_time'];

    protected string|array $quickSearchField = ['id'];

    protected array $noNeedPermission = ['*'];

    public function initialize(): void
    {
        parent::initialize();
        $this->model = new \app\admin\model\Fields();
    }
    
    public function generate(){
        $params = $this->request->param();
        $number = intval($params['number']);
       
        $res = Queue::push('app\jobs\GenerateDataJob@generateData', ['number'=>$number,'name'=>$params['name']],'generateData');
        if($res){
            $this->success('数据生成中，请稍后刷新数据');
        }
        $this->error('数据生成失败');
    }
    /**
     * 保存字段配置
     */
    public function save(){
        $params = $this->request->param();
        Db::startTrans();
        try{
            $this->model->where('name',$params['name'])->delete();
            foreach($params['filed_item'] as $item){
                \app\admin\model\Fields::create(['name'=>$params['name'],'field_item'=>$item]);
            }
            if($params['is_del'] == 1){
                //清空表
                Db::query('TRUNCATE TABLE ba_'.$params['name']);
                // Db::name($params['name'])->where('id','>',0)->delete();
            }
            Db::commit();
        }catch(\Exception $e){
            Db::rollback();
            $this->error($e->getMessage());
        }
        $this->success('保存成功');
    }
    public function getInfo(){
        
        $name = $this->request->param('name');
        $field_item = [];
        $list = $this->model->where('name',$name)->field('field_item')->select()->toArray();
        foreach($list as $item){
            $field_item[] = $item['field_item'];
        }
        $stores = Store::group('name')->field('name')->select();
        $store_list = [];
        foreach($stores as $k => $v){
            $store_list[] = [
                'label' => $v['name'],
                'value' => $v['name'],
            ];
        }
        $this->success('',[
            'table_name' => $name,
            'field_item' => $field_item,
            'store_list' => $store_list,
            'loading' => false
        ]);
    }

    /**
     * 若需重写查看、编辑、删除等方法，请复制 @see \app\admin\library\traits\Backend 中对应的方法至此进行重写
     */
}